package org.javagril.yuetong.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.javagril.yuetong.bean.RespBean;
import org.javagril.yuetong.bean.User;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {
    @PostMapping("/doLogin")
    public RespBean doLogin(@RequestBody User user) {
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(user.getAccount(), user.getPassword()));

            /*返回数据 password 不会返回在浏览器*/
            User user1 = (User) subject.getSession().getAttribute("user");
            user1.setPassword("");

            return RespBean.ok("登录成功",user1);
        } catch (AuthenticationException e) {
            e.printStackTrace();
        }
        return RespBean.error("登录失败");
    }
}
